package com.haizhi.vp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haizhi.vp.entity.*;
import com.haizhi.vp.enums.CityWeatherEnum;
import com.haizhi.vp.mapper.*;
import com.haizhi.vp.service.WordService;
import com.haizhi.vp.utils.GenWordUtil;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class WordServiceImpl implements WordService {

    @Autowired
    private TomorrowBdInfoMapper tomorrowBdInfoMapper;
    @Autowired
    private TomorrowDutyInfoMapper tomorrowDutyInfoMapper;
    @Autowired
    private BdImportantMatterMapper bdImportantMatterMapper;
    @Autowired
    private BdInfoMapper bdInfoMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OnlineInspectionInfoMapper onlineInspectionInfoMapper;
    @Autowired
    private DutyInfoMapper dutyInfoMapper;
    @Autowired
    private EmergencyResponseInfoMapper emergencyResponseInfoMapper;

    @Autowired
    private LineFailureInfoMapper lineFailureInfoMapper;

    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日");
    private static final SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
    private static final SimpleDateFormat sf1 = new SimpleDateFormat("yyyy年MM月dd日");

    @Override
    public void GenWord() {
        Document document = new Document();

        //1、基础模板的替换
        GenWordUtil.genWord(document, "/opt/shudian/ribao/ribao.doc", buildBaseInfo());
        Section section = document.getSections().get(0);
        //1、基本情况
        buildBase(section);
        //2\主要工作
        mainWork(section);
        //3重要事项
        bdImportMatter(section);
        //4明日工作安排
        tomorrowWork(section);

        document.encrypt("Gsdl@2022..");

        document.saveToFile("/opt/shudian/ribao/" + sf.format(new Date()) + ".docx", FileFormat.Docx);
    }

    /**
     * 构建基本信息
     *
     * @return
     */
    private Map<String, String> buildBaseInfo() {

        Map<String, String> baseInfo = new HashMap<>();
        baseInfo.put("${date}", simpleDateFormat.format(new Date()));
        baseInfo.put("${one}", "2");
        return baseInfo;
    }


    /**
     * 构建第一个模块
     */
    private void buildBase(Section section) {

        GenWordUtil.createTitle(section, "一、基本情况");
        GenWordUtil.createText(section, "1.基本情况");
        GenWordUtil.createText(section, simpleDateFormat.format(new Date()) + "，甘肃公司架空输电线路运行正常，对" + 1100 + "条重点线路进行重点保障，安全生产、网络与信息系统安全运行，无舆情和不稳定事件，保电形势平稳。");
        //天气情况
        weather(section);
        //设备异常
        GenWordUtil.createText(section, "3.设备异常");
        Map<String, Object> map = new HashMap<>();
        map.put("create_date", sf.format(new Date()));
        List<LineFailureInfo> lineFailureInfos = this.lineFailureInfoMapper.selectByMap(map);
        if (!CollectionUtils.isEmpty(lineFailureInfos)) {
            for (LineFailureInfo failureInfo : lineFailureInfos) {
                String text = sf1.format(new Date()) + failureInfo.getFaultTime() + "," +
                        "" + failureInfo.getVlevel() + failureInfo.getLineName() + failureInfo.getFaultProfile() + ","
                        + failureInfo.getSuccessful() + ",故障原因" + failureInfo.getFaultReason() + "," + "线路已与" + failureInfo.getRecoveryTime() + "恢复运行";
                GenWordUtil.createText(section, text);
            }
        } else {
            GenWordUtil.createText(section, "今日无设备异常情况。");
        }

    }


    /**
     * 主要工作模块
     */
    private void mainWork(Section section) {
        GenWordUtil.createTitle(section, "二、主要工作");
        //值班情况
        dutyInfo(section);
        //保电详情
        bdInfo(section);
        //应急响应情况
        yjInfo(section);

    }

    /**
     * 重要事项
     */
    private void bdImportMatter(Section section) {
        GenWordUtil.createTitle(section, "三、重要事项");
        Map<String, Object> map = new HashMap<>();
        map.put("create_date", sf.format(new Date()));
        List<BdImportantMatter> bdImportantMatters = bdImportantMatterMapper.selectByMap(map);

        if (CollectionUtils.isEmpty(bdImportantMatters)) {
            GenWordUtil.createText(section, "无重大事项。");
        } else {

        }
    }

    /**
     * 明日工作安排
     */
    private void tomorrowWork(Section section) {
        GenWordUtil.createTitle(section, "四、明日工作安排");
        //值班安排
        tomorrowDutyInfo(section);
        //保电工作安排
        TommorrowBdInfo(section);
        //明日重大事项
        importThings(section);
    }

    /**
     * 明日重大保电事项
     *
     * @param section
     */
    private void importThings(Section section) {
        GenWordUtil.createText(section, "3.明日重大事项");
        GenWordUtil.createText(section, "8：00-14：00二十大开幕，进入特级保电时段。");
    }

    /**
     * 构建保电情况
     *
     * @param section
     */
    private void TommorrowBdInfo(Section section) {
        GenWordUtil.createText(section, "2.保电工作安排");
        Map<String, Double> count = tomorrowBdInfoMapper.getCount(sf.format(new Date()));
        Double group_count = count.get("group_count");
        Double person_count = count.get("person_count");
        Double car_count = count.get("car_count");
        Double rtz_count = count.get("rtz_count");
        Double line_count = count.get("line_count");
        Double tower_count = count.get("tower_count");
        Double km_count = count.get("km_count");
        Double yh_count = count.get("yh_count");
        Double yh_person = count.get("yh_person");
        Double yh_group = count.get("yh_group");
        Double cy_group = count.get("cy_group");
        Double cy_person = count.get("cy_person");
        Double cy_car = count.get("cy_car");
        Double cy_rtz = count.get("cy_rtz");
        Double cy_line = count.get("cy_line");
        GenWordUtil.createText(section, "出动巡视人员" + group_count.intValue() + "组、" + person_count.intValue() + "人、车辆" + car_count.intValue() + "台、" +
                "无人机1" + rtz_count.intValue() + "架开展保电特巡，巡视线路" + line_count.intValue() + "条、杆塔" + tower_count.intValue() + "基、" + km_count + "公里；" +
                "对" + yh_count.intValue() + "处隐患出动" + yh_group.intValue() + "组、" + yh_person.intValue() + "人进行蹲守。其中对跨森林草原线路" + cy_line.intValue() + "条、" +
                "出动" + cy_group.intValue() + "组、" + cy_person.intValue() + "人、车辆" + cy_car.intValue() + "台、无人机" + cy_rtz.intValue() + "架进行特巡。");


        Map<String, Object> map = new HashMap<>();
        map.put("create_date", sf.format(new Date()));
        List<BdInfo> bdInfos = bdInfoMapper.selectByMap(map);
        List<String> header = new ArrayList<>();
        //单位	出动巡视人员	巡视线路（条）	杆塔数	公里数	隐患蹲守	跨森林草原区段
        //	组	人数	车辆	无人机				隐患点（处）	组	人数	线路条数	组	人数	车辆	无人机
        header.add("单位");
        header.add("组");
        header.add("人数");
        header.add("车辆");
        header.add("无人机");
        header.add("巡视线路（条）");
        header.add("杆塔数");
        header.add("公里数");
        header.add("隐患点（处）");
        header.add("隐患组");
        header.add("隐患人数");
        header.add("草原线路条数");
        header.add("草原组");
        header.add("草原人数");
        header.add("草原车辆");
        header.add("草原无人机");
        List<List<Object>> data = new ArrayList<>();
        for (BdInfo bdInfo : bdInfos) {
            List<Object> list = new ArrayList<>();
            list.add(bdInfo.getCompany());
            list.add(bdInfo.getGroupCount());
            list.add(bdInfo.getPersonCount());
            list.add(bdInfo.getCarCount());
            list.add(bdInfo.getRtzCount());
            list.add(bdInfo.getLineCount());
            list.add(bdInfo.getTowerCount());
            list.add(bdInfo.getKmCount());
            list.add(bdInfo.getYhCount());
            list.add(bdInfo.getYhGroup());
            list.add(bdInfo.getYhPerson());
            list.add(bdInfo.getCyLine());
            list.add(bdInfo.getCyGroup());
            list.add(bdInfo.getCyPerson());
            list.add(bdInfo.getCyCar());
            list.add(bdInfo.getCyRtz());
            data.add(list);
        }
        GenWordUtil.createDoc(section, header, data);
    }

    /**
     * 明日值班安排
     *
     * @param section
     */
    private void tomorrowDutyInfo(Section section) {
        Map<String, Object> map = new HashMap<>();
        map.put("create_date", sf.format(new Date()));
        List<TomorrowDutyInfo> dutyInfos = tomorrowDutyInfoMapper.selectByMap(map);
        GenWordUtil.createText(section, "1.值班安排");
        GenWordUtil.createText(section, "明日值班人员共" + dutyInfos.size() + "人、监控班开展24小时值班。");
        List<String> header = new ArrayList<>();
        //单位	日    期	值班时间	值班人员	值班座机	手机号码
        header.add("单位");
        header.add("日   期");
        header.add("值班时间");
        header.add("值班人员");
        header.add("值班座机");
        header.add("手机号码");
        header.add("24小时值班");
        List<List<Object>> data = new ArrayList<>();
        for (TomorrowDutyInfo dutyInfo : dutyInfos) {
            List<Object> list = new ArrayList<>();
            list.add(dutyInfo.getCompany());
            list.add(dutyInfo.getDate());
            list.add(dutyInfo.getTime());
            list.add(dutyInfo.getOperator());
            list.add(dutyInfo.getPlane());
            list.add(dutyInfo.getPhone());
            list.add(dutyInfo.getHour24());
            data.add(list);
        }
        GenWordUtil.createDoc(section, header, data);
    }

    /**
     * 天气情况
     *
     * @param section
     */
    private void weather(Section section) {
        GenWordUtil.createText(section, "2.天气情况");
        //14加公司的天气  接口、、https://restapi.amap.com/v3/weather/weatherInfo?key=acfd24b76abe0a60df2596761212f27d&city=620104&extensions=all
        //https://restapi.amap.com/v3/weather/weatherInfo?key=acfd24b76abe0a60df2596761212f27d&extensions=base&city=620423
        /**
         * {
         * "status": "1",
         * "count": "1",
         * "info": "OK",
         * "infocode": "10000",
         * "lives": [
         * {
         * "province": "甘肃",
         * "city": "景泰县",
         * "adcode": "620423",
         * "weather": "晴",
         * "temperature": "15",
         * "winddirection": "南",
         * "windpower": "≤3",
         * "humidity": "20",
         * "reporttime": "2022-10-16 11:07:57"
         * }
         * ]
         * }
         */
        List<WeatherVo> lists = new ArrayList<>();
        for (CityWeatherEnum value : CityWeatherEnum.values()) {
            String[] split = value.getCodeList().split(",");
            for (String s : split) {
                String url = "https://restapi.amap.com/v3/weather/weatherInfo?key=acfd24b76abe0a60df2596761212f27d&extensions=base&city=" + s;
                ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(url, JSONObject.class);
                JSONObject body = responseEntity.getBody();
                if (body != null && body.getString("status").equals("1")) {
                    JSONArray lives = body.getJSONArray("lives");
                    List<Map> maps = lives.toJavaList(Map.class);
                    WeatherVo weatherVo = new WeatherVo();
                    log.info("获取到的天气情况是{}", maps);
                    Object city = maps.get(0).get("city");
                    Object weather = maps.get(0).get("weather");
                    Object humidity = maps.get(0).get("humidity");
                    Object temperature = maps.get(0).get("temperature");

                    weatherVo.setWeather(weather);
                    weatherVo.setHumidity(humidity + "%");
                    weatherVo.setTemperature(temperature + "℃");
                    weatherVo.setCity(value.getName());
                    weatherVo.setCounty(city);
                    lists.add(weatherVo);
                }
            }
        }
        List<String> header = new ArrayList<>();
        header.add("地市");
        header.add("县区");
        header.add("天气");
        header.add("气温");
        header.add("湿度");

        List<List<Object>> data = new ArrayList<>();
        for (WeatherVo info : lists) {
            List<Object> list = new ArrayList<>();
            list.add(info.getCity());
            list.add(info.getCounty());
            list.add(info.getWeather());
            list.add(info.getTemperature());
            list.add(info.getHumidity());
            data.add(list);
        }
        // 县区 天气 气温 湿度
        GenWordUtil.createDoc(section, header, data);
    }

    /**
     * 值班情况
     *
     * @param section
     */
    private void dutyInfo(Section section) {
        GenWordUtil.createText(section, "1.值班情况");

        Map<String, Object> map = new HashMap<>();
        map.put("create_date", sf.format(new Date()));
        List<DutyInfo> dutyInfos = dutyInfoMapper.selectByMap(map);
        GenWordUtil.createText(section, "今日值班人员共" + dutyInfos.size() + "人、监控班开展24小时值班。");
        List<String> header = new ArrayList<>();
        //单位	日    期	值班时间	值班人员	值班座机	手机号码
        header.add("单位");
        header.add("日   期");
        header.add("值班时间");
        header.add("值班人员");
        header.add("值班座机");
        header.add("手机号码");
        List<List<Object>> data = new ArrayList<>();
        for (DutyInfo dutyInfo : dutyInfos) {
            List<Object> list = new ArrayList<>();
            list.add(dutyInfo.getCompany());
            list.add(dutyInfo.getDate());
            list.add(dutyInfo.getTime());
            list.add(dutyInfo.getOperator());
            list.add(dutyInfo.getPlane());
            list.add(dutyInfo.getPhone());
            data.add(list);
        }
        GenWordUtil.createDoc(section, header, data);
        //设备数量
        deviceInfo(section);
    }

    /**
     * 设备数量
     *
     * @param section
     */
    private void deviceInfo(Section section) {
        Map<String, Double> count = this.onlineInspectionInfoMapper.getCount(sf.format(new Date()));
        Double visual_oline = count.get("visual_oline");

        Double visual_count = count.get("visual_count");
        Double ice_oline = count.get("ice_oline");
        Double ice_count = count.get("ice_count");
        Double factory_oline = count.get("factory_oline");
        Double factory_count = count.get("factory_count");
        GenWordUtil.createText(section, "可视化在线监测" + visual_count.intValue() + "台、在线" + visual_oline.intValue() + "台，" +
                "覆冰在线监测" + ice_count.intValue() + "台、在线" + ice_oline.intValue() + "台，" +
                "分布式故障诊断装置" + factory_count.intValue() + "台、在线" + factory_oline.intValue() + "台，均处于有效监控状态，不在线为设备故障。");


        Map<String, Object> map = new HashMap<>();
        map.put("create_date", sf.format(new Date()));
        List<OnlineInspectionInfo> onlineInspectionInfos = onlineInspectionInfoMapper.selectByMap(map);

        List<String> header = new ArrayList<>();
        //单位	日    期	值班时间	值班人员	值班座机	手机号码
        header.add("单位");
        header.add("可视化合计");
        header.add("可视化在线");
        header.add("覆冰合计");
        header.add("覆冰在线");
        header.add("分布式合计");
        header.add("分布式在线");
        header.add("备注");
        List<List<Object>> data = new ArrayList<>();
        for (OnlineInspectionInfo info : onlineInspectionInfos) {
            List<Object> list = new ArrayList<>();
            list.add(info.getCompany());
            list.add(info.getVisualCount());
            list.add(info.getVisualOline());
            list.add(info.getIceCount());
            list.add(info.getIceOline());
            list.add(info.getFactoryCount());
            list.add(info.getFactoryOline());
            list.add(info.getDes());
            data.add(list);
        }
        GenWordUtil.createDoc(section, header, data);
    }


    /**
     * 构建保电情况
     *
     * @param section
     */
    private void bdInfo(Section section) {
        GenWordUtil.createText(section, "2.保电开展情况");
        Map<String, Double> count = bdInfoMapper.getCount(sf.format(new Date()));
        Double group_count = count.get("group_count");
        Double person_count = count.get("person_count");
        Double car_count = count.get("car_count");
        Double rtz_count = count.get("rtz_count");
        Double line_count = count.get("line_count");
        Double tower_count = count.get("tower_count");
        Double km_count = count.get("km_count");
        Double yh_count = count.get("yh_count");
        Double yh_person = count.get("yh_person");
        Double yh_group = count.get("yh_group");
        Double cy_group = count.get("cy_group");
        Double cy_person = count.get("cy_person");
        Double cy_car = count.get("cy_car");
        Double cy_rtz = count.get("cy_rtz");
        Double cy_line = count.get("cy_line");
        GenWordUtil.createText(section, "出动巡视人员" + group_count.intValue() + "组、" + person_count.intValue() + "人、车辆" + car_count.intValue() + "台、" +
                "无人机1" + rtz_count.intValue() + "架开展保电特巡，巡视线路" + line_count.intValue() + "条、杆塔" + tower_count.intValue() + "基、" + km_count + "公里；" +
                "对" + yh_count.intValue() + "处隐患出动" + yh_group.intValue() + "组、" + yh_person.intValue() + "人进行蹲守。其中对跨森林草原线路" + cy_line.intValue() + "条、" +
                "出动" + cy_group.intValue() + "组、" + cy_person.intValue() + "人、车辆" + cy_car.intValue() + "台、无人机" + cy_rtz.intValue() + "架进行特巡。");


        Map<String, Object> map = new HashMap<>();
        map.put("create_date", sf.format(new Date()));
        List<BdInfo> bdInfos = bdInfoMapper.selectByMap(map);
        List<String> header = new ArrayList<>();
        //单位	出动巡视人员	巡视线路（条）	杆塔数	公里数	隐患蹲守	跨森林草原区段
        //	组	人数	车辆	无人机				隐患点（处）	组	人数	线路条数	组	人数	车辆	无人机
        header.add("单位");
        header.add("组");
        header.add("人数");
        header.add("车辆");
        header.add("无人机");
        header.add("巡视线路（条）");
        header.add("杆塔数");
        header.add("公里数");
        header.add("隐患点（处）");
        header.add("隐患组");
        header.add("隐患人数");
        header.add("草原线路条数");
        header.add("草原组");
        header.add("草原人数");
        header.add("草原车辆");
        header.add("草原无人机");
        List<List<Object>> data = new ArrayList<>();
        for (BdInfo bdInfo : bdInfos) {
            List<Object> list = new ArrayList<>();
            list.add(bdInfo.getCompany());
            list.add(bdInfo.getGroupCount());
            list.add(bdInfo.getPersonCount());
            list.add(bdInfo.getCarCount());
            list.add(bdInfo.getRtzCount());
            list.add(bdInfo.getLineCount());
            list.add(bdInfo.getTowerCount());
            list.add(bdInfo.getKmCount());
            list.add(bdInfo.getYhCount());
            list.add(bdInfo.getYhGroup());
            list.add(bdInfo.getYhPerson());
            list.add(bdInfo.getCyLine());
            list.add(bdInfo.getCyGroup());
            list.add(bdInfo.getCyPerson());
            list.add(bdInfo.getCyCar());
            list.add(bdInfo.getCyRtz());
            data.add(list);
        }
        GenWordUtil.createDoc(section, header, data);
    }


    /**
     * 应急响应情况
     *
     * @param section
     */
    private void yjInfo(Section section) {
        Map<String, Object> map = new HashMap<>();
        map.put("create_date", sf.format(new Date()));
        List<EmergencyResponseInfo> responseInfos = emergencyResponseInfoMapper.selectByMap(map);
        Map<String, Double> count = emergencyResponseInfoMapper.getCount(sf.format(new Date()));
        Double team = count.get("team");
        Double person = count.get("person");
        GenWordUtil.createText(section, "3.应急响应情况");
        GenWordUtil.createText(section, "共有" + team.intValue() + "支队伍、" + person.intValue() + "名抢修人员待命。");

        //单位	队伍	抢修人员	应急处置
        //			时间	线路名称	处置情况

        List<String> header = new ArrayList<>();
        //单位	日    期	值班时间	值班人员	值班座机	手机号码
        header.add("单位");
        header.add("队伍");
        header.add("抢修人员");
        header.add("时间");
        header.add("线路名称");
        header.add("处置情况");
        List<List<Object>> data = new ArrayList<>();
        for (EmergencyResponseInfo info : responseInfos) {
            List<Object> list = new ArrayList<>();
            list.add(info.getCompany());
            list.add(info.getTeam());
            list.add(info.getPerson());
            list.add(info.getTime());
            list.add(info.getLine());
            list.add(info.getDispositionInfo());
            data.add(list);
        }
        GenWordUtil.createDoc(section, header, data);
    }
}
